/****************************************************************************
 *
 * Copyright (C) 2003-2010 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.dataset.squid;

import java.sql.Timestamp;
import java.util.StringTokenizer;
import nfse.NetFSERecord;
import nfse.NetFSEUtil;
import nfse.gui.server.GUIRecordFactory;
import nfse.gui.server.RecordBuilderUtil;

public class SquidRecordFactory extends GUIRecordFactory<SquidRecord> {

    public SquidRecordFactory() {
        builder = new RecordBuilderUtil();
        builder.addColumn(null, "id", RecordBuilderUtil.BIGINT);
        RecordBuilderUtil.SQLField field = builder.addColumn("Start TS", "startts", RecordBuilderUtil.TIMESTAMP);
        field = builder.addColumn("Duration", "duration", RecordBuilderUtil.INTEGER);
        field = builder.addColumn("Src IP", "srcip", RecordBuilderUtil.INET);
        field = builder.addColumn("Dst IP/Host", "dstiphost", RecordBuilderUtil.VARCHAR, 500);
        field = builder.addColumn("Dst bytes", "dstbytes", RecordBuilderUtil.BIGINT);
        field = builder.addColumn("HTTP Method", "httpmethod", RecordBuilderUtil.VARCHAR, 100);
        field = builder.addColumn("HTTP Status", "httpstatus", RecordBuilderUtil.INTEGER);
        field = builder.addColumn("URL", "url", RecordBuilderUtil.VARCHAR, 1000);
        field = builder.addColumn("Result", "squidresult", RecordBuilderUtil.VARCHAR, 100);
        field = builder.addColumn("MIME Type", "mimetype", RecordBuilderUtil.VARCHAR, 100);
        field = builder.addColumn("Client Info", "clientinfo", RecordBuilderUtil.VARCHAR, 1000);
    }

    @Override
    protected void setValues(SquidRecord record, int id) {
        int idx = -1;
        builder.setFieldValue(++idx, "" + id);
        builder.setFieldValue(++idx, record.getTimestamp().toString());
        builder.setFieldValue(++idx, "" + record.duration);
        builder.setFieldValue(++idx, record.getSrcAddr());
        builder.setFieldValue(++idx, record.getDstHost());
        builder.setFieldValue(++idx, "" + record.dstBytes);
        builder.setFieldValue(++idx, record.httpMethod);
        builder.setFieldValue(++idx, "" + record.httpStatus);
        builder.setFieldValue(++idx, NetFSEUtil.prepareValueForInsert(record.url));
        builder.setFieldValue(++idx, record.squidResult);
        builder.setFieldValue(++idx, NetFSEUtil.prepareValueForInsert(record.mimeType));
        builder.setFieldValue(++idx, NetFSEUtil.prepareValueForInsert(record.clientInfo));
    }

    public NetFSERecord generate() {
        return new SquidRecord();
    }

    public NetFSERecord generate(String line, int sensor) throws Exception {
        /**
         * According to http://wiki.squid-cache.org/SquidFaq/SquidLogs the
         * format is: time elapsed remotehost code/status bytes method URL
         * rfc931 peerstatus/peerhost type
         */
        try {
            SquidRecord temp = new SquidRecord();
            temp.setInitialString(line);
            temp.setTypeName("Squid");
            temp.setTypeID(typeID);
            temp.setSensorID(sensor);

            int colIdx = line.indexOf(":", 15);

            line = line.substring(colIdx + 1);

            StringTokenizer st = new StringTokenizer(line);
            if (st.countTokens() < SquidRecord.EXPECTED_TOKENS) {
                return null;
            }

            temp.setStartTS(new Timestamp((long) (Double.parseDouble(st.nextToken()) * 1000.0)));
            temp.duration = Integer.parseInt(st.nextToken());
            temp.setSrcAddr(st.nextToken());
            String val3 = st.nextToken();
            String[] val3Tokens = val3.split("/");
            temp.squidResult = val3Tokens[0];
            temp.httpStatus = Integer.parseInt(val3Tokens[1]);

            temp.dstBytes = Long.parseLong(st.nextToken());

            // The next token is one of GET/POST/CONNECT
            temp.httpMethod = st.nextToken();

            temp.url = st.nextToken();
            String val7 = st.nextToken();
            String dstStr = st.nextToken(); // The destination, if any
            if (dstStr.startsWith("DIRECT/")) {
                try {
                    temp.setDstIP(NetFSEUtil.convertIPtoLong(dstStr.substring(7)));
                } catch (Exception e) {
                    // System.out.println(line);

                    // This is a hostname, not an IP, save in dstHost
                    temp.dstHost = dstStr.substring(7);
                }
            }

            temp.mimeType = st.nextToken();

            if (st.hasMoreTokens()) {
                // There are at least 11 tokens but maybe more.
                // The remaining tokens are the browser/client info
                temp.clientInfo = st.nextToken();
                if (temp.clientInfo.length() > 0 && temp.clientInfo.charAt(0) == '"')
                    temp.clientInfo = temp.clientInfo.substring(1);
                while (st.hasMoreTokens()) {
                    temp.clientInfo += " " + st.nextToken();
                }
                if (temp.clientInfo.length() > 0 && temp.clientInfo.charAt(temp.clientInfo.length() - 1) == '"') {
                    temp.clientInfo = temp.clientInfo.substring(0, temp.clientInfo.length() - 1);
                }
            } else {
                temp.clientInfo = "";
            }
            return temp;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
